#!/usr/bin/python
# Author: Michael Saunby.
# 
# Purpose. Add simple marker styles to KML
#

# Configuration

import sys, urllib
import cgi
#import cgitb; cgitb.enable()

stylesURI = "http://wemapr.s3.amazonaws.com/styles.kml#"

def getArgs():
    global url, styleId, kind
    form = cgi.FieldStorage()

    url = form["url"].value
    styleId = form["style"].value
    kind = form["kind"].value

if __name__ == "__main__":
    from xml.dom.minidom import parse

    getArgs()
    if kind == "kml":
      doc = parse(urllib.urlopen(url))
    else:
      src="http://pipes.yahoo.com/pipes/pipe.run?_id=QtW0WlhS3BGeRrmxl7okhQ&_render=kml&feed="+urllib.quote(url,'')
      doc = parse(urllib.urlopen(src))
      pass
    places = doc.getElementsByTagName("Placemark")
    for i in range(len(places)):
      style = doc.createElement("styleUrl")
      style.appendChild(doc.createTextNode(stylesURI+styleId))
      places[i].appendChild(style)

    print "Content-type: application/vnd.google-earth.kml+xml\n"
    print doc.toxml()
